package com.qf.fmw.servlet;


import com.qf.fmw.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
    //登录
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端发送的请求数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //连接数据库判断用户名和密码是否正确
        Connection connection = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        int count = 0;
        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM admin WHERE username = ? AND password = ?");
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            //执行sql语句并获取结果集
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(resultSet, preparedStatement, connection);
        }
        if (count == 0) {
            request.setAttribute("msg", "用户名或者密码错误");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        response.sendRedirect("userIndex.jsp");
    }
}
